--- 模块功能：ftp上传日志
-- @module ftpUpdateLog
-- @author zhangfengfe
-- @license MIT
-- @copyright OpenLuat.com
-- @release 2024.05.07
module(..., package.seeall)
require "ftp"
require "nvm"
require "logUploadHttp"
require "logGenerator"

-- 配置文件初始化
nvm.init("config.lua", true)
-- 挂载SD卡
-- io.mount(io.SDCARD)
-- 参数初始化
local filePath = ""
-- 配置参数初始化
local ftpHost, ftpPort, ftpName, ftpPsw, clientNo = nvm.get("centerConfig")[16],
                                                    nvm.get("centerConfig")[17],
                                                    nvm.get("centerConfig")[18],
                                                    nvm.get("centerConfig")[19],
                                                    nvm.get("info")[1]
local function ftpUpdateLog(oneFilePath)
    local r, n = ftp.login("PASV", ftpHost, ftpPort, ftpName, ftpPsw) -- 登录
    log.info("ftp_login", r, n)
    if r ~= "200" then return end
    r, n = ftp.pwd() -- 显示工作目录
    log.info("ftp_pwd", r, n)
    if r == "426" or r == "503" then
        return
    elseif n:match(logGenerator.LOG_DIR_PATH) == nil then
        r, n = ftp.mkd(logGenerator.LOG_DIR_PATH) -- 创建目录
        log.info("ftp_mkd", r, n)
        if r == "426" or r == "503" then return end
        r, n = ftp.cwd(logGenerator.LOG_DIR_PATH) -- 切换目录
        log.info("ftp_cwd", r, n)
        if r == "426" or r == "503" then return end
    end
    if io.exists(oneFilePath) then
        r, n = ftp.upload(oneFilePath, oneFilePath) -- 上传log文件
        log.info("ftp_log", r, n)
        if r ~= "200" then return end
    end
    ftp.close()
end
function FtpUploadLogs()
    local date = string.format("%04d-%02d-%02d", os.date("*t").year,
                               os.date("*t").month, os.date("*t").day)
    local fileName = clientNo .. "-" .. date
    filePath = logGenerator.LOG_DIR_PATH .. "/" .. fileName .. "-log.txt"
    ftpUpdateLog(filePath)
    filePath = logGenerator.LOG_DIR_PATH .. "/" .. fileName .. "-eqlog.txt"
    ftpUpdateLog(filePath)
    filePath = logGenerator.LOG_DIR_PATH .. "/" .. fileName .. "-error.txt"
    ftpUpdateLog(filePath)
    filePath = logGenerator.LOG_DIR_PATH .. "/" .. fileName .. "-selfCheck.txt"
    ftpUpdateLog(filePath)
end
-- 卸载SD卡
-- io.unmount(io.SDCARD)
